﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace DotNET4Study
{
    class ParallelStudy
    {
        public static void Excute()
        {
            ////1.并行处理图片
            //ImageProcess(@"E:\test", "jpg"); 

            //2.并行计算与普通方式的比较
            CompareToCommon();
        }

        private static void CompareToCommon()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 50; i++)
            {
                Thread.Sleep(50);
            }
            sw.Stop();
            Console.WriteLine("使用普通方式的循环耗时{0}",sw.Elapsed.TotalMilliseconds);

            sw.Restart();
            Parallel.For(0,50,x=>Thread.Sleep(50));
            sw.Stop();
            Console.WriteLine("使用并行方式的循环耗时{0}", sw.Elapsed.TotalMilliseconds);
        }

        private static void ImageProcess(string originalImagesPath,string imagesExtName)
        {
            if (imagesExtName.StartsWith(".") == false)
            {
                imagesExtName = "." + imagesExtName;
            }
            // A simple source for demonstration purposes. Modify this path as necessary.
            string[] files = System.IO.Directory.GetFiles(originalImagesPath, "*"+imagesExtName);
            string newDir = originalImagesPath+"\\Modified";
            System.IO.Directory.CreateDirectory(newDir);

            //  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
            Parallel.ForEach(files, currentFile =>
            {
                // The more computational work you do here, the greater 
                // the speedup compared to a sequential foreach loop.
                string filename = System.IO.Path.GetFileName(currentFile);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);

                bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                bitmap.Save(System.IO.Path.Combine(newDir, filename));

                // Peek behind the scenes to see how work is parallelized.
                // But be aware: Thread contention for the Console slows down parallel loops!!!
                Console.WriteLine("Processing {0} on thread {1}", filename,
                                    Thread.CurrentThread.ManagedThreadId);

            } //close lambda expression
                 ); //close method invocation

            // Keep the console window open in debug mode.
            Console.WriteLine("Processing complete. Press any key to exit.");
            //Console.ReadKey();
        }
    }
}
